package com.keepalive_kotlin.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import com.blankj.utilcode.util.AppUtils
import com.keepalive_kotlin.R

/**
 * 电池优化工具类
 * 用于请求电池优化白名单，提高保活效果
 */
object BatteryOptimizationUtil {

    /**
     * 检查是否已忽略电池优化
     */
    @SuppressLint("BatteryLife")
    fun isIgnoringBatteryOptimization(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            powerManager.isIgnoringBatteryOptimizations(context.packageName)
        } else {
            true
        }
    }

    /**
     * 请求忽略电池优化
     */
    @SuppressLint("BatteryLife")
    fun requestIgnoreBatteryOptimization(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.data = Uri.parse("package:${activity.packageName}")
                activity.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                // 如果无法直接跳转到电池优化设置页面，则跳转到电池优化列表页面
                requestIgnoreBatteryOptimizationGeneral(activity)
            }
        }
    }

    /**
     * 通用方式请求忽略电池优化（跳转到电池优化列表）
     */
    private fun requestIgnoreBatteryOptimizationGeneral(activity: Activity) {
        try {
            val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 显示电池优化提示对话框
     */
    fun showBatteryOptimizationDialog(activity: Activity, onConfirm: (() -> Unit)?) {
        val dialog = AlertDialog.Builder(activity)
            .setTitle("电池优化设置")
            .setMessage("为了确保应用在后台正常运行，请将本应用添加到电池优化白名单中。")
            .setPositiveButton("去设置") { _, _ ->
                requestIgnoreBatteryOptimization(activity)
                onConfirm?.invoke()
            }
            .setNegativeButton("取消", null)
            .show()
            
        // 设置对话框宽度，防止超出屏幕
        val window = dialog.window
        if (window != null) {
            val displayMetrics = DisplayMetrics()
            activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
            val width = (displayMetrics.widthPixels * 0.9).toInt() // 设置为屏幕宽度的90%
            window.setLayout(width, WindowManager.LayoutParams.WRAP_CONTENT)
        }
    }
}